package com.zkj.fileupload;

import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.util.List;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.commons.fileupload.FileItem;
import org.apache.commons.fileupload.FileUploadException;
import org.apache.commons.fileupload.disk.DiskFileItemFactory;
import org.apache.commons.fileupload.servlet.ServletFileUpload;

public class FileUpload extends HttpServlet {

	@Override
	protected void doGet(HttpServletRequest req, HttpServletResponse resp)
			throws ServletException, IOException {
		DiskFileItemFactory fileItemFactory = new DiskFileItemFactory();
		ServletFileUpload sfu = new ServletFileUpload(fileItemFactory);
		try {
			List<FileItem> list = sfu.parseRequest(req);
			for (FileItem f : list) {
				if (f.isFormField()) {
					String fieldName = f.getFieldName();
					String fieldValue = f.getString();
					System.out.println(fieldName + fieldValue);
				} else {
					// 文件
					// 文件要写入的磁盘位置
					String fileDirpath = getServletContext().getRealPath(
							"/file");
					InputStream in = f.getInputStream();
					String uploadFileName = f.getName();
					if (f.getName().contains("\\")) {
						uploadFileName = f.getName().substring(
								f.getName().lastIndexOf("\\") + 1);
					}
					OutputStream out = new FileOutputStream(fileDirpath + "\\"
							+ uploadFileName);
					int len = -1;
					byte[] b = new byte[1024];
					while ((len = in.read(b)) != -1) {
						out.write(b, 0, len);
					}
					in.close();
					out.close();
				}

			}
		} catch (FileUploadException e) {
			e.printStackTrace();
		}

	}

	@Override
	protected void doPost(HttpServletRequest req, HttpServletResponse resp)
			throws ServletException, IOException {
		// TODO Auto-generated method stub

		doGet(req, resp);
	}

}
